<?php

namespace app\admin\service\auth;

use app\admin\model\auth\MenuModel;
use app\admin\model\Admin;
use think\facade\Db;
use think\Collection;
use app\admin\service\BaseService;

class MenuService extends BaseService
{
    /**
     * 获取列表
     * @param $data
     * @return mixed
     */
    public function getList($jwt)
    {
      $adminID = $jwt['id'];
      $menuTree = MenuModel::getMenuTreeByAdmin($adminID);
      return success($menuTree);
    }
    /**
     * 添加
     * @param $data
     * @return mixed
     */
    public function Add($data)
    {
      $model = new MenuModel();
      if($data['pid']===''){
        return fail('请选择上级菜单');
      }

      $name = isset($data['path']) ? trim($data['path']) : '';
      $name = ltrim($name, '/');
      if ($name !== '') {
        $name = ucfirst($name);
      }
      $data['name'] = $name;
      if($data['type']==1){
        $path = isset($data['path']) ? trim($data['path']) : '';
        if ($path !== '' && strpos($path, '/') !== 0) {
          $path = '/' . $path;
        }
        $data['path'] = $path;
        $data['component'] = '/index/index';
        $data['permission'] = '/';
      }
      Db::startTrans();
        try{
            $data['created_at'] = time();
            $model->insert($data);
            Db::commit();
            $this->writeLog('添加', 1);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 编辑
     * @param $id
     * @param $data
     * @return mixed
     */
    public function Edit($id, $data)
    {
      $model = new MenuModel();
      $res = $model->where('id', $id)->find();
      if (empty($res)) {
        return fail('菜单不存在');
      }
      switch ($res->type) {
        case 1:
            $allow = ['title', 'icon', 'sort', 'status','path'];
            break;
        case 2:
            $allow = ['title', 'icon', 'sort', 'status','path','component', 'permission'];
            break;
        case 3:
            $allow = ['title', 'permission', 'sort'];
            break;
        default:
            return fail('未知类型');
      }
      $uniqueFields = ['permission'];
      $requiredFields = ['title'];
      $data['id'] = $id;
      $check = $this->checkParams($model, $data, $uniqueFields, $requiredFields);
      if ($check !== true) {
        return fail($check['msg']);
      }
      $updateData = array_intersect_key($data, array_flip($allow));
      if (empty($updateData)) {
          return fail('没有可修改的字段');
      }
      Db::startTrans();
        try{
            $updateData['updated_at'] = time();
            $model->where('id', $id)->update($updateData);
            Db::commit();
            $this->writeLog('编辑', 2);
            return success([],'操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 删除
     * @param $ids
     * @return mixed
     */
    public function Delete($ids)
    {
      $model = new MenuModel();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
      }
      $ids = array_map('intval', $ids);
      $hasChild = $model->whereIn('pid', $ids)->count();
      if ($hasChild > 0) {
          return fail('当前删除存在下级菜单或权限，请先删除下级菜单或权限');
      }
      try {
          Db::name('role_menu')->whereIn('menu_id', $ids)->delete();
          $res = $model->whereIn('id', $ids)->delete();
          if ($res === false) {
            Db::rollback();
            return fail('删除失败');
          }
          $this->writeLog('删除'. implode(',', $ids), 3);
          return success();
      } catch (\Exception $e) {
          return fail('系统错误'.$e->getMessage());
      }
    }
}
